package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrOctetString;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.nio.ByteBuffer;

public class SignatureSecurity extends AxdrType {
    private ByteBuffer dataCode = null;
    private AxdrOctetString p2 = null;
    private AxdrOctetString s2 = null;

    public void setDataCode(ByteBuffer dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(AxdrOctetString p2, AxdrOctetString s2) {
        this.p2 = p2;
        this.s2 = s2;
    }

    public void setP1(AxdrOctetString p2) {
        this.p2 = p2;
    }

    public void setS1(AxdrOctetString s2) {
        this.s2 = s2;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.p2 = new AxdrOctetString();
        codeLength += this.p2.decode(input);
        this.s2 = new AxdrOctetString();
        codeLength += this.s2.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            codeLength = this.dataCode.remaining();
            while (this.dataCode.hasRemaining()) {
                output.write(this.dataCode.get());
            }
        } else {
            if (this.p2 != null && this.s2 != null) {
                codeLength += this.s2.encode(output);
                codeLength += this.p2.encode(output);
            } else {
                throw new Exception("p2 or s2 is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = ByteBuffer.wrap(revOStream.toByteArray());
    }

    @Override
    public String toString() {
        if (this.p2 != null && this.s2 != null) {
            return "sequence: {" + "p2: " + this.p2 + ", s2: " + this.s2 + "}";
        } else {
            return "p2 or s2 is null";
        }
    }
}



